package com.xin.di.uav.applet.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 签名示例
 */
public class SignatureUtils {

    public static void main(String[] args) {
        String appKey = "e12c25d7db4a38670206d8c897bf0f34";
        String reqTime = String.valueOf(System.currentTimeMillis());//String.valueOf(System.currentTimeMillis());
//        String requestBody = "{\n" +
//                "    \"requestId\": \"AAABcjbmCjWQT5CZCGahi5mjX1\",\n" +
//                "    \"templateCode\": \"fm_210_standard_eos-scp-core\",\n" +
//                "    \"fileType\": \"pdf\",\n" +
//                "    \"sync\": \"true\",\n" +
//                "    \"documents\": [\n" +
//                "        {\n" +
//                "            \"masterWaybillNo\": \"SF1310191706763\",\n" +
//                "            \"waybillNoCheckType\": \"2\",\n" +
//                "            \"waybillNoCheckValue\": \"071383\",\n" +
//                "            \"remark\": \"备注\"\n" +
//                "        }\n" +
//                "    ],\n" +
//                "    \"version\": \"2.0\"\n" +
//                "}";
//        String requestBody =
//                "{                                                        "
//                        + "   \"requestId\":\"123\",                               "
//                        + "   \"templateCode\": \"fm_210_standard_IE-UOCS-CORE\",  "
//                        + "   \"documents\": [{                                    "
//                        + "   \"masterWaybillNo\": \"SF1380034785341\",            "
//                        + "     \"waybillNoCheckType\": \"1\",                     "
//                        + "     \"waybillNoCheckValue\": \"666667\"                "
//                        + "   }]                                                   "
//                        + "}     " +
//                        "                                                  ";
//

        String requestBody = "{\n" +
                "    \"requestId\": \"88229280870\",\n" +
                "    \"templateCode\": \"fm_210_standard_IE-UOCS-CORE\",\n" +
                "    \"fileType\": \"pdf\",\n" +
                "    \"sync\": \"true\",\n" +
                "    \"documents\": [\n" +
                "        {\n" +
                "            \"masterWaybillNo\": \"SF1380034785341\",\n" +
                "            \"waybillNoCheckType\": \"1\",\n" +
                "            \"waybillNoCheckValue\": \"666667\",\n" +
                "            \"remark\": \"备注\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"version\": \"2.0\"\n" +
                "}";
        JSONObject params = JSONObject.parseObject(requestBody, Feature.OrderedField);
        String signature = genSignature(params, reqTime, appKey);
        System.out.println("signature:" + signature);//signature:2bb7bcd12a03771e3a8b441434be051d
    }

    /**
     * 签名算法
     *
     * @param params
     * @param reqTime
     * @param appKey
     * @return
     */
    public static String genSignature(JSONObject params, String reqTime, String appKey) {
        Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
        StringJoiner joiner = new StringJoiner("&");
        TreeMap<String, String> map = new TreeMap<>(Comparator.naturalOrder());
        map.put("appKey", appKey);
        map.put("reqTime", reqTime);
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            map.put(entry.getKey(), entry.getValue().toString());
        }
        map.entrySet().forEach(entry -> {
            if (StringUtils.isNotBlank(entry.getValue())) {
                joiner.add(entry.getKey() + "=" + entry.getValue());
            }
        });
        try {
            return DigestUtils.md5DigestAsHex(joiner.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }


    public static String generateOpenSign(String postData, Long appId, String appKey) {
        StringBuilder sb = new StringBuilder();
        sb.append(postData);
        sb.append("&" + appId + "&" + appKey);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] md5 = new byte[0];
        try {
            md5 = md.digest(sb.toString().getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        int i;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < md5.length; offset++) {
            i = md5[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }

        String ret = null;


        return ret;
    }
}